package com.todo.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.todo.demo.Dao.PlanAndTaskDao;
import com.todo.demo.Model.*;
import com.todo.demo.Service.LoginService;
import com.todo.demo.Service.PlanAndTaskService;
import com.todo.demo.Service.WebService;
import com.todo.demo.Util.HttpRequest;
import com.todo.demo.Util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/templates")
public class html {
    @Autowired
    private WebService planAndTaskService;
    @Autowired
    private LoginService userService;
    @Autowired
    private PlanAndTaskService planAndTaskServiceReal;

    @RequestMapping("/h")
    public String index(ModelMap map) {
        // 加入一个属性，用来在模板中读取
        map.addAttribute("name", getIndex(map, 1, 10, false));

        return "ttt";
    }

    @RequestMapping("/getPlan")
    @ResponseBody
    public List<UserWithPlan> getPlan(Integer pageNum, Integer pageSize, boolean ishuoyue) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 15;
        }
        return getIndex(new ModelMap(), pageNum, pageSize, ishuoyue);
    }

    @RequestMapping(value = "/t", method = RequestMethod.POST)
    @ResponseBody
    public String getTask(String planId) {
        List<Task> taskList = planAndTaskService.getTaskByPlanId(Long.valueOf(planId));
        for (int i = 0; i < taskList.size(); i++) {
            if (taskList.get(i).getTask_user_id() != 0) {
                User userCreator = new User();
                userCreator.setId(taskList.get(i).getTask_user_id());
                userCreator = userService.getUserById(userCreator);

                if (userCreator != null) {
                    if (userCreator.getNick_name() != null)
                        taskList.get(i).setCreator(userCreator.getNick_name());
                    else
                        taskList.get(i).setCreator("");
                }
            } else {
                taskList.get(i).setCreator("");
            }
        }
        return JSON.toJSON(taskList).toString();
    }

    public ArrayList<UserWithPlan> getIndex(ModelMap map, Integer pageNum, Integer pageSize, boolean ishuoyue) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 15;
        }

        List<UserWithPlan> planList = new ArrayList<>();

        if (ishuoyue) {
            planList = planAndTaskService.getAllPlan(pageNum, pageSize);
        } else {
            planList = planAndTaskService.findhuoyuePlan(pageNum, pageSize);
        }

        ArrayList<UserWithPlan> planArrayList = new ArrayList<>();

        if (planList.size() > 0) {
            if (ishuoyue) {
                planList.get(0).setCount(planAndTaskService.findhuoyuePlanCount());
            } else {
                planList.get(0).setCount(planAndTaskService.findAllPlanCount());
            }
        }

        for (int i = 0; i < planList.size(); i++) {
            UserWithPlan plan = planList.get(i);

            User userCreator = new User();
            userCreator.setId(plan.getPlan_user_id());
            userCreator = userService.getUserById(userCreator);
            if (userCreator.getNick_name() != null)
                plan.setCreator(userCreator.getNick_name());
            else
                plan.setCreator("");

            /**
             *  去查合作人，转换成中文名字
             */
            if (plan.getParnters() == null || plan.getParnters().equals("")) {
                plan.setParnters("");
                plan.setUserName("");
            } else {
                String[] ps = plan.getParnters().split(",");
                String name = "";

                for (int x = 0; x < ps.length; x++) {
                    User user1 = new User();

                    user1.setId(Integer.parseInt(ps[x]));
                    User user2 = userService.getUserById(user1);

                    if (user2 != null)
                        name = name + "," + user2.getNick_name();
                }
                name = name.replaceFirst(",", "");
                plan.setUserName(name);
            }

            if (userCreator.getLast_login_time() == null) {
                plan.setLast_login_time("");
            } else {
                plan.setLast_login_time(userCreator.getLast_login_time());
            }

            if (plan.getLast_edit_time() == null) {
                plan.setLast_edit_time("");
            } else {
                plan.setLast_edit_time(plan.getLast_edit_time());
            }
            planArrayList.add(plan);
        }


        return planArrayList;
    }

    @RequestMapping("/getUser")
    @ResponseBody
    public List<User> getUser(Integer pageNum, Integer pageSize, boolean ishuoyue) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 15;
        }

        List<User> userList = new ArrayList<>();
        if (ishuoyue) {
            userList = userService.selectHuoyueUsers(pageNum, pageSize);
            if (userList.size() > 0) {
                userList.get(0).setCount(userService.selectHuoyueUsersCount());
            }
        } else {
            userList = userService.findAllUser(pageNum, pageSize);
            if (userList.size() > 0) {
                userList.get(0).setCount(userService.selectUsersCount());
            }
        }

        return userList;
    }

    @RequestMapping("/pushAll")
    @ResponseBody
    public String pushAll() {
        int sendSucCount = 0;
        int sendFailCount = 0;

        List<User> userList = userService.findAllUser(1, 10000);
        String msg = "";

        for (int i = 0; i < userList.size(); i++) {
            int day = 0;
            try {
                day = Util.getInstance().calculateTimeDifferenceByCalendar(String.valueOf(userList.get(i).getLast_login_time()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            if (day > 4) {
                System.out.println("准备给【" + userList.get(i).getNick_name() + "】发消息...");

                String res;

                if (userService.getAccessToken() == null) {
                    res = sendMsg(String.valueOf(userList.get(i).getId()), Util.getInstance().getToken(userService));
                } else {
                    res = sendMsg(String.valueOf(userList.get(i).getId()), (String) userService.getAccessToken().getTodo_value());
                }
                if (res.equals("没有计划")) {
                    sendFailCount++;
                    continue;
                }

                JSONObject jsonObject1 = (JSONObject) JSON.parse(res);
                if (jsonObject1.getInteger("errcode") == 42001 || jsonObject1.getInteger("errcode") == 40001) {
                    res = sendMsg(String.valueOf(userList.get(i).getId()), Util.getInstance().getToken(userService));
                }

                jsonObject1 = (JSONObject) JSON.parse(res);
                if (jsonObject1.getInteger("errcode") == 0) {
                    sendSucCount++;
                } else if (jsonObject1.getInteger("errcode") == 41029) {
                    sendFailCount++;
                } else if (jsonObject1.getInteger("errcode") == 41028) {
                    sendFailCount++;
                } else {
                    sendFailCount++;
                }

                System.out.println("发送消息执行完成，结果：" + res);
            }

            msg = "发送成功" + sendSucCount + "人，发送失败" + sendFailCount + "人";
        }

        return JSON.toJSONString(msg);
    }

    @RequestMapping("/pushById")
    @ResponseBody
    public String pushById(long user_id) {
        String res;
        String msg = "";

        if (userService.getAccessToken() == null) {
            res = sendMsg(String.valueOf(user_id), Util.getInstance().getToken(userService));
        } else {
            res = sendMsg(String.valueOf(user_id), (String) userService.getAccessToken().getTodo_value());
        }
        if (res.equals("没有计划")) {
            msg = "失败，已经发送过1条，等用户再次使用才能发送";
            return msg;
        }
        JSONObject jsonObject1 = (JSONObject) JSON.parse(res);
        if (jsonObject1.getInteger("errcode") == 42001 || jsonObject1.getInteger("errcode") == 40001) {
            res = sendMsg(String.valueOf(user_id), Util.getInstance().getToken(userService));
        }
        jsonObject1 = (JSONObject) JSON.parse(res);

        if (jsonObject1.getInteger("errcode") == 0) {
            msg = "成功";
        } else if (jsonObject1.getInteger("errcode") == 41029) {
            msg = "失败，已经发送过1条，等用户再次使用才能发送";
        } else if (jsonObject1.getInteger("errcode") == 41028) {
            msg = "失败，formId过期，等用户再次使用才能发送";
        } else {
            msg = "失败，原因未知";
        }
        return JSON.toJSONString(msg);
    }


    private String sendMsg(String userId, String access_token) {
        User user = new User();
        user.setId(Long.valueOf(userId));

        User user1 = userService.getUserById(user);
        List<HashMap<String, Object>> plans = planAndTaskServiceReal.findAllPlanWithTask(1, 100, Long.valueOf(userId));
        if (plans.size() <= 0) {
            return "没有计划";
        }
        Plan plan = (Plan) plans.get(0).get("plan");
        String plan_title = plan.getPlan_title();
        String plan_create_time = plan.getPlan_create_time();

        /**
         *  发送消息
         */

        String params;

        /**
         *  data
         */
        KeyWord keyWord = new KeyWord();
        KeyWord.KeywordValue keyWordValue = new KeyWord().new KeywordValue();
        keyWordValue.setValue("鲁迅说：没有完成计划的人，不要吃饭");
        keyWord.setKeyword1(keyWordValue);
        keyWordValue = new KeyWord().new KeywordValue();
        keyWordValue.setValue(plan_title);
        keyWord.setKeyword2(keyWordValue);
        keyWordValue = new KeyWord().new KeywordValue();
        keyWordValue.setValue(plan_create_time);
        keyWord.setKeyword3(keyWordValue);

        /**
         *  总体
         */
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("touser", user1.getUser_name());
        paramsMap.put("template_id", "8A2Gh9i9V5QafAWkb7uGn2agCkuqpb5O86tOwGJfHxQ");
        paramsMap.put("form_id", user1.getForm_id());
        paramsMap.put("page", "pages/index/index");
        paramsMap.put("data", keyWord);

        params = JSON.toJSONString(paramsMap);
        /**
         * 发送模板消息的参数
         */

        String res = Util.getInstance().post("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?&access_token=" + access_token, params);

        JSONObject map = (JSONObject) JSONObject.parse(res);

        MsgLog msgLog = new MsgLog();
        msgLog.setCode(map.get("errcode").toString());
        msgLog.setError_msg(map.get("errmsg").toString());
        msgLog.setUser_id(Long.valueOf(userId));
        /**
         * 获取系统时间
         */
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        msgLog.setSend_time(df.format(new Date()));

        userService.addMsgLog(msgLog);
        return res;
    }

    @RequestMapping("/MsgLog")
    @ResponseBody
    public Object MsgLog(int pageNum, int pageSize) {
        List<MsgLog> msgLogList = planAndTaskService.getMsgLog(pageNum, pageSize);
        for (int i = 0; i < msgLogList.size(); i++) {
            if (msgLogList.get(i).getCode().equals("40001")) {
                msgLogList.remove(i);
            }
        }

        if (msgLogList.size() > 0) {
            msgLogList.get(0).setCount(String.valueOf(planAndTaskService.getMsgLogCount()));
        }
        return msgLogList;
    }
}